package com.bit.ThreadTest.newTest;

import java.util.concurrent.Semaphore;

//信号量
public class TestSemaphore {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {

                try {
                    //先申请资源
                    System.out.println("尝试申请");
                    semaphore.acquire();
                    System.out.println("成功");
                    //申请到再睡眠
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //再释放资源
                semaphore.release();
                System.out.println("释放");
            }
        };
        for (int i = 0; i < 20; i++) {
            Thread thread = new Thread(runnable);
            thread.start();
        }
    }
}
